package com.molyfun.parents.view.RecordView;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.PowerManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.molyfun.parents.R;
import com.molyfun.parents.im.ChatRowVoicePlayClickListener;
import com.molyfun.parents.utils.ErrorCode;
import com.molyfun.parents.utils.FileUtils;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:10/18/16.
 */
public class VoiceRecorderView extends RelativeLayout {
    protected Context context;
    protected LayoutInflater inflater;
    protected Drawable[] micImages;
    protected VoiceRecorder voiceRecorder;

    protected PowerManager.WakeLock wakeLock;
    protected ImageView micImage;
    protected TextView recordingHint;
    private TextView mSecond;
    private int mCurrentSecond = 0;

    private int MAX_SECOND = 60;

    private static final int FLAG_RECORD_EVENT = 1001;

    private static final int REFRESH_TIME_SECOND = 1000;

    protected Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            // change image
            micImage.setImageDrawable(micImages[msg.what]);
        }
    };

    protected Handler timeRecordeHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case FLAG_RECORD_EVENT:
                    timeRecordeHandler.sendEmptyMessageDelayed(FLAG_RECORD_EVENT, REFRESH_TIME_SECOND);
                    mCurrentSecond++;
                    mSecond.setText((MAX_SECOND - mCurrentSecond) + "s");
                    if (mCurrentSecond >= 60) {
                        timeRecordeHandler.removeMessages(FLAG_RECORD_EVENT);
                        if(mV != null){
                            mV.setPressed(false);
                        }
                        onPressedActionUp();
                        mIsActionDown = false;
                    }
                    break;
            }
        }
    };

    public VoiceRecorderView(Context context) {
        super(context);
        init(context);
    }

    public VoiceRecorderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public VoiceRecorderView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.widget_voice_recorder, this);

        micImage = (ImageView) findViewById(R.id.mic_image);
        recordingHint = (TextView) findViewById(R.id.recording_hint);
        mSecond = (TextView) findViewById(R.id.second);

        voiceRecorder = new VoiceRecorder(micImageHandler);

        // animation resources, used for recording
        micImages = new Drawable[]{getResources().getDrawable(R.mipmap.ic_voice_img_6),
                getResources().getDrawable(R.mipmap.ic_voice_img_6),
                getResources().getDrawable(R.mipmap.ic_voice_img_6),
                getResources().getDrawable(R.mipmap.ic_voice_img_6),
                getResources().getDrawable(R.mipmap.ic_voice_img_6),
                getResources().getDrawable(R.mipmap.ic_voice_img_6),};

        wakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
    }

    private VoiceRecorderCallback mVoiceRecorderCallback;
    private View mV;

    /**
     * on speak button touched
     *
     * @param v
     * @param event
     */
    public boolean onPressToSpeakBtnTouch(View v, MotionEvent event, VoiceRecorderCallback recorderCallback) {
        mVoiceRecorderCallback = recorderCallback;
        mV = v;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                try {
                    if (ChatRowVoicePlayClickListener.isPlaying)
                        ChatRowVoicePlayClickListener.currentPlayListener.stopPlayVoice();
                    v.setPressed(true);
                    mSecond.setText("60s");
//                    com.molyfun.parents.im.ChatRowVoicePlayClickListener.currentPlayListener.stopPlayVoice();
                    startRecording();
                    mIsActionDown = true;
                } catch (Exception e) {
                    v.setPressed(false);
                }
                return true;
            case MotionEvent.ACTION_MOVE:
                if (event.getY() < 0) {
                    showReleaseToCancelHint();
                } else {
                    showMoveUpToCancelHint();
                }
                return true;
            case MotionEvent.ACTION_UP:
                v.setPressed(false);
                if (event.getY() < 0) {
                    // discard the recorded audio.
                    discardRecording();
                } else {
                    onPressedActionUp();
                }
                mIsActionDown = false;
                return true;
            default:
                discardRecording();
                return false;
        }
    }

    private boolean mIsActionDown = false;

    private synchronized void onPressedActionUp() {
        if(!mIsActionDown){
            return;
        }
        // stop recording and send voice file
        mCurrentSecond = 0;
        if(timeRecordeHandler.hasMessages(FLAG_RECORD_EVENT)){
            timeRecordeHandler.removeMessages(FLAG_RECORD_EVENT);
        }
        try {
            int length = stopRecoding();
            if (length > 0) {
                if (mVoiceRecorderCallback != null) {
                    mVoiceRecorderCallback.onVoiceRecordComplete(getVoiceFilePath(), length);
                }
            } else if (length == ErrorCode.FILE_INVALID) {
                Toast.makeText(context, R.string.Recording_without_permission, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, R.string.The_recording_time_is_too_short, Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, R.string.send_failure_please, Toast.LENGTH_SHORT).show();
        }
    }

    public interface VoiceRecorderCallback {
        /**
         * on voice record complete
         *
         * @param voiceFilePath   录音完毕后的文件路径
         * @param voiceTimeLength 录音时长
         */
        void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength);
    }

    public void startRecording() {
        if (!FileUtils.isSDCardMounted()) {
            Toast.makeText(context, R.string.Send_voice_need_sdcard_support, Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            wakeLock.acquire();
            this.setVisibility(View.VISIBLE);

            micImage.setImageResource(R.mipmap.ic_voice_img_6);
            recordingHint.setText(context.getString(R.string.move_up_to_cancel));
            recordingHint.setBackgroundColor(Color.TRANSPARENT);
            voiceRecorder.startRecording(context);
            timeRecordeHandler.sendEmptyMessageDelayed(FLAG_RECORD_EVENT, REFRESH_TIME_SECOND);
        } catch (Exception e) {
            e.printStackTrace();
            if (wakeLock.isHeld())
                wakeLock.release();
            if (voiceRecorder != null)
                voiceRecorder.discardRecording();
            this.setVisibility(View.INVISIBLE);
            Toast.makeText(context, R.string.recoding_fail, Toast.LENGTH_SHORT).show();
            return;
        }
    }

    public void showReleaseToCancelHint() {
        recordingHint.setText(context.getString(R.string.release_to_cancel));
        micImage.setImageResource(R.mipmap.ic_voice_img_6_del);
        recordingHint.setBackgroundResource(R.drawable.recording_text_hint_bg);
    }

    public void showMoveUpToCancelHint() {
        recordingHint.setText(context.getString(R.string.move_up_to_cancel));
        micImage.setImageResource(R.mipmap.ic_voice_img_6);
        recordingHint.setBackgroundColor(Color.TRANSPARENT);
    }

    public void discardRecording() {
        if (wakeLock.isHeld())
            wakeLock.release();
        try {
            // stop recording
            if (voiceRecorder.isRecording()) {
                voiceRecorder.discardRecording();
                this.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
        }
    }

    public int stopRecoding() {
        this.setVisibility(View.INVISIBLE);
        if (wakeLock.isHeld())
            wakeLock.release();
        return voiceRecorder.stopRecoding();
    }

    public String getVoiceFilePath() {
        return voiceRecorder.getVoiceFilePath();
    }

    public String getVoiceFileName() {
        return voiceRecorder.getVoiceFileName();
    }

    public boolean isRecording() {
        return voiceRecorder.isRecording();
    }

}
